import { ref, reactive } from "vue";
import { logout, updatePassword } from "~/api/manager";
import { showModal, toast } from "~/composables/util.js";
import { useRouter } from "vue-router";
import { useStore } from "vuex";

// 修改密码
export function useRepassword() {
  const router = useRouter();
  const store = useStore();

  // 修改密码
  const FormDrawerRef = ref(null);
  // 定义form
  const form = reactive({
    repassword: "",
    oldpassword: "",
    password: "",
  });

  // 验证规则
  const rules = {
    oldpassword: [
      { required: true, message: "旧密码不能为空", trigger: "blur" },
      // 长度在3-5之间
      // { min: 3, max: 5, message: '用户名长度必须是3-5个', trigger: 'blur' }
    ],
    password: [{ required: true, message: "新密码不能为空", trigger: "blur" }],
    repassword: [
      { required: true, message: "确认密码不能为空", trigger: "blur" },
    ],
  };

  const formRef = ref(null);

  const onSubmit = () => {
    FormDrawerRef.value.showLoading(); // 按钮上的加载效果
    console.log("submit!");
    formRef.value.validate((valid) => {
      if (!valid) {
        loading.value = false;
        return false;
      }
      console.log("验证通过");
      updatePassword(form)
        .then((res) => {
          toast("修改密码成功，请重新登录！");
          store.dispatch("logout");
          // 跳转到登录页
          router.push("/login");
        })
        .finally(() => {
          FormDrawerRef.value.hideLoading();
        });
    });
  };

  const openRePasswordForm = () => FormDrawerRef.value.open();

  return {
    FormDrawerRef,
    form,
    rules,
    formRef,
    onSubmit,
    openRePasswordForm,
  };
}

// 退出登录
export function useLogout() {
  const router = useRouter();
  const store = useStore();

  function handleLogout() {
    showModal("是否要退出登录？").then((res) => {
      console.log("退出登录");
      logout().finally(() => {
        store.dispatch("logout");
        // 跳转到登录页
        router.push("/login");
        // 提示退出登录成功
        toast("退出登录成功");
      });
    });
  }
  return { handleLogout };
}
